package com.secondriver.url.admin.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.secondriver.url.admin.groovy.AdminServiceDao;

public class AdminServlet extends HttpServlet {

	private static final long serialVersionUID = 1737806018967194703L;

	private AdminServiceDao adminServiceDao;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json; charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		Map<?, ?> requestParameterMap = (Map<?, ?>) request.getParameterMap();
		Map<Object, Object> params = new HashMap<Object, Object>();
		Iterator<?> iter = requestParameterMap.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<?, ?> entry = (Entry<?, ?>) iter.next();
			Object key = entry.getKey();
			Object value = entry.getValue();
			if (value instanceof String[]) {
				String[] values = (String[]) value;
				if (values.length == 1) {
					params.put(key, values[0]);
				}
			} else {
				params.put(key, value);
			}
		}
		String result = (String) adminServiceDao.service(params);
		System.out.println(result);
		response.getWriter().println(result);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String dbConfig = config.getInitParameter("dbConfig");
		adminServiceDao = new AdminServiceDao(dbConfig);
	}
}
